﻿using FaceRecognition.Model;
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.IO;
using OpenCvSharp;
using OpenCvSharp.Extensions;
using System.Threading;

namespace FaceRecognition
{
    public partial class FrmFaceInput : Form
    {
        private Redis_DAL.GetData mGetData = null;
        private Redis_DAL.SetData mSetData = null;

        private ImageInfo mInfo = null;

        private bool mIsUpdate = false;
        public FrmFaceInput(ImageInfo mi = null)
        {
            InitializeComponent();
            mGetData = new Redis_DAL.GetData();
            mSetData = new Redis_DAL.SetData();
            if (mi != null)
                this.mInfo = mi;
        }

        private delegate void AsyncAction();

        private int mCount = 0;

        /// <summary>
        /// 如果是修改信息，该属性保存旧的人名，确保在重新拍摄后照片一样会更改
        /// </summary>
        private string mOldName = string.Empty;

        private bool mIsTake = true;
        private Thread th = null;

        /// <summary>
        /// 图片保存的路径
        /// </summary>
        private string mImgPath = Application.StartupPath+"\\DataSource\\Images";

        private void FrmFaceInput_Load(object sender, EventArgs e)
        {
            try
            {
                this.pictureBox1.Paint += PictureBox1_Paint;
                th = new Thread(ShowUSBCamare);
                th.Start();

                if (this.mInfo != null)
                {
                    this.textBox1.Text = this.mInfo.ImageID + "";
                    this.textBox2.Text = this.mInfo.Name;
                    this.mOldName = this.mInfo.Name;
                    if(this.mInfo.Gender.Equals("男"))
                    {
                        this.radioButton1.Checked = true;
                    }
                    else
                    {
                        this.radioButton2.Checked = true;
                    }

                    if(File.Exists(Application.StartupPath + this.mInfo.HeadImage))
                    {
                        //以流的形式显示图片，不然作删除时会占用文件
                        using (FileStream fs = new FileStream(Application.StartupPath + this.mInfo.HeadImage, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            Image img = Image.FromStream(fs);
                            Bitmap map = (Bitmap)img.Clone();
                            img.Dispose();
                            this.pictureBox1.Image = map;
                        }
                    }
                    this.mIsUpdate = true;
                    this.mCount = this.mInfo.ImageGroupID;
                }
                else
                {
                    this.mInfo = new ImageInfo();
                    string count = this.mGetData.GetKey<string>("FaceCount");
                    this.mCount = Convert.ToInt32(count);
                    this.textBox1.Text = this.mCount + 1 + "";
                }
              

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// 打开摄像头
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            this.mIsTake = false;
        }

        private Bitmap imgShow = null;
        private void ShowUSBCamare()
        {
            try
            {
                Mat src = new Mat();
                FrameSource frame = Cv2.CreateFrameSource_Camera(0);
                while (true)
                {
                    if (!mIsTake)
                    {
                        frame.NextFrame(src);
                        Bitmap bitmap = BitmapConverter.ToBitmap(src);
                        this.imgShow = (Bitmap)bitmap.Clone();
                        pictureBox1.Invalidate();
                    }

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private void PictureBox1_Paint(object sender, PaintEventArgs e)
        {
            if (this.imgShow == null)
                return;
            //e.Graphics.DrawImage(imgShow, 0, 0,320,240);
            this.pictureBox1.Image = this.imgShow;
        }



        /// <summary>
        /// 拍摄
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            this.mIsTake = true;
        }


        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.textBox2.Text))
                {
                    MessageBox.Show("名称不能为空");
                    return;
                }

                if (this.pictureBox1.Image == null)
                {
                    MessageBox.Show("请拍照");
                    return;
                }

                if (File.Exists(mImgPath + "\\" + this.mOldName + ".jpg"))
                {
                    File.Delete(mImgPath + "\\" + this.mOldName + ".jpg");
                }

                Bitmap img = new Bitmap(this.pictureBox1.Image);
                if (!Directory.Exists(this.mImgPath))
                    Directory.CreateDirectory(this.mImgPath);
                string savePath = this.mImgPath + "\\" + this.textBox2.Text + ".jpg";
                if (File.Exists(savePath))
                    File.Delete(savePath);

                img.Save(savePath, ImageFormat.Jpeg);
             
                if (this.mIsUpdate)
                {
                    mInfo.Name = this.textBox2.Text;
                    mInfo.Gender = this.radioButton1.Checked ? "男" : "女";
                    mInfo.Image = null;
                    mInfo.HeadImage = "\\DataSource\\Images\\" + this.textBox2.Text + ".jpg";
                    mSetData.UploadList<ImageInfo>("Users", mInfo.ImageGroupID, mInfo);
                   
                }
                else
                {
                    mInfo.ImageID = this.mCount + 1;
                    mInfo.Name = this.textBox2.Text;
                    mInfo.Image = null;
                    mInfo.Gender = this.radioButton1.Checked ? "男" : "女";
                    mInfo.HeadImage = "\\DataSource\\Images\\" + this.textBox2.Text + ".jpg";
                    mInfo.ImageGroupID = this.mCount;

                    mSetData.AddList<ImageInfo>("Users", mInfo);
                    mSetData.AddKey("FaceCount", this.mCount + 1);
                }
              

                MessageBox.Show("保存成功!");
                this.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmFaceInput_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(this.th != null)
            {
               this.th.Interrupt();   
                //while(this.th.ThreadState != ThreadState.Aborted)
                //{
                //    Thread.Sleep(100);
                //}
            }
        }
    }
}
